package bb.lanxing.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.model.data.LessonData;

public class LessonAdapter extends RecyclerView.Adapter<LessonAdapter.ViewHolder> {
    private List<LessonData> list = new ArrayList<>();
    private OnItemClickListener listener;
    private Context mContext;

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView title;
        TextView remark;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            title = itemView.findViewById(R.id.title);
            remark = itemView.findViewById(R.id.remark);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_lesson, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (list != null) {
            LessonData lessonData = list.get(position);
            if (lessonData != null) {
                Glide.with(mContext).load(lessonData.fullImageUrl).into(holder.imageView);
                holder.title.setText(lessonData.title);
                holder.remark.setText(lessonData.remark);
                holder.itemView.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onItemClick(position);
                    }
                });
            }
        }
    }

    @Override
    public int getItemCount() {
        if (list != null) {
            return list.size();
        }
        return 0;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void updateData(List<LessonData> dataList) {
        list = dataList;
        notifyDataSetChanged();
    }
}